


local Grid = class("Grid")

-- Game Grid
function Grid:ctor(width, height)
    self.super:ctor()
    self.grid=nil
    self.width=width or 10
    self.height=height or 16
    self.animDelay=100
    self.animTime=0
    self.isAnim=false

    self.grid={}
    for y=1,self.height do
        self.grid[y]={}
        for x=1,self.width do
            self.grid[y][x] = g.service.const.EMPTY_CELL_SPR
        end
    end
end


function Grid:register()

end

function Grid:Draw(cx,cy)
    for y=1,self.height do
        for x=1,self.width do
            local id = self.grid[y][x]
            local color = "red"
            if id == g.service.const.EMPTY_CELL_SPR then
                color = "brack"
            end
            g.service.ui:createSprite(cx+x-1,cy+y-1, color)
        end
    end
end

function Grid:Add(x,y,sprId)
    self.grid[y][x]=sprId
end

function Grid:UpdateLine()
    local res=0
    for y=1,self.height do
        local isLine = true
        for x=1,self.width do
            isLine = isLine and not (self.grid[y][x] == g.service.const.EMPTY_CELL_SPR)
            if not isLine then break end
        end

        if isLine then
            res=res+1
            self.isAnim = true
            self.animTime = os.time()
            for x=1,self.width do
                self.grid[y][x] = g.service.const.DIE1_CELL_SPR
            end
        end
    end
    return res
end

function Grid:replace(oldSprId, newSprId)
    local res = false
    for y=1,self.height do
        for x=1,self.width do
            if self.grid[y][x] == oldSprId then
                self.grid[y][x]=newSprId
                res = true
            end
        end
    end
    return res
end

function Grid:removeLine(gridLine)
    table.remove(self.grid, gridLine)
    local newLine={}
    for x=1,self.width do
        newLine[x] = g.service.const.EMPTY_CELL_SPR
    end
    table.insert(self.grid,1,newLine)
end

function Grid:remove(oldSprId)
    local process=true
    while process do
        process=false
        for y=1,self.height do
            if self.grid[y][1] == oldSprId then
                self:removeLine(y)
                process=true
                break
            end
        end
    end
end

function Grid:AnimationUpdate()
    if not self.isAnim then return end
    local now = time()
    if now > self.animTime + self.animDelay then
        self.animTime=now
        self:remove(g.service.const.DIE2_CELL_SPR)
        self.isAnim = self:replace(g.service.const.DIE1_CELL_SPR, g.service.const.DIE2_CELL_SPR)
    end
end



return Grid
